﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WebHome_API.Models;
using WebHome_API.Models.DBModels;
using WebHome_API.Models.OperResult;

namespace WebHome_API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        [HttpGet("getConfigOfAPP")]
        public OperResult<Config> getConfigOfAPP()
        {
            var userCode = Request.Headers["userCode"].ToString();
            Config ret = new();
            using (MyContext context = new())
            {
                var cur = context.Users.FirstOrDefault(u => u.Code == userCode.ToLower());

                if (cur == null)
                {
                    //生成默认的
                    ret = createDefaultConfig(context);
                }
                else
                {
                    //导出指定的
                    if (string.IsNullOrEmpty(cur.Config))
                    {
                        //生成默认的
                        ret = createDefaultConfig(context);
                        cur.Config = JsonConvert.SerializeObject(ret);
                        context.SaveChanges();
                    }
                    else
                    {
                        ret = JsonConvert.DeserializeObject<Config>(cur.Config);
                    }
                }
            }
            return OperResult<Config>.Succeed(ret);
        }

        [HttpGet("createDefaultConfig")]
        public OperResult<Config> createDefaultConfig()
        {
            var userCode = Request.Headers["userCode"].ToString();
            using (MyContext context = new())
            {
                var user = context.Users.FirstOrDefault(u => u.Code == userCode.ToLower());
                if (user != null)
                {
                    Config config = createDefaultConfig(context);
                    user.Config = JsonConvert.SerializeObject(config);

                    if (context.SaveChanges() == 1 || context.SaveChanges() == 0)
                        return OperResult<Config>.Succeed(config);
                    else
                        return OperResult<Config>.Failed("save error");
                }
            }
            return OperResult<Config>.Failed("userCode is NULL");
        }

        [HttpPost("uploadConfig")]
        public OperResult uploadConfig(
           int randomOrder,
           string nickName,
           string messageList,
           int messageLookId
            )
        {
            var userCode = Request.Headers["userCode"].ToString();
            using (MyContext context = new())
            {
                var cur = context.Users.FirstOrDefault(u => u.Code == userCode.ToLower());
                if (cur != null)
                {
                    Config config;
                    if (string.IsNullOrEmpty(cur.Config))
                        config = createDefaultConfig(context);
                    else
                        config = JsonConvert.DeserializeObject<Config>(cur.Config)!;

                    config.RandomOrder = randomOrder;
                    if (nickName != "default-sy")
                    {
                        config.NickName = nickName;
                    }
                    if (messageList != "0")
                    {
                        var tempMessageList = new List<int>();
                        foreach (var item in messageList.Split(","))
                        {
                            tempMessageList.Add(Convert.ToInt32(item));
                        }
                        config.MessageList = tempMessageList;
                    }
                    config.MessageLookId = messageLookId;
                    cur.Config = JsonConvert.SerializeObject(config);
                    context.SaveChanges();
                    return OperResult.Succeed();
                }
            }
            return OperResult.Failed("userCode is NULL");
        }

        [HttpGet("Login")]
        public OperResult<Config> Login(string userCode)
        {
            using (MyContext context = new())
            {
                var user = context.Users.FirstOrDefault(u => u.Code == userCode.ToLower());
                if (user != null)
                {
                    if (string.IsNullOrEmpty(user.Config))
                    {
                        var temp = createDefaultConfig(context);
                        //创建新的
                        user.Config = JsonConvert.SerializeObject(temp);
                        context.SaveChanges();
                        return OperResult<Config>.Succeed(temp);
                    }
                    else
                    {
                        var temp = JsonConvert.DeserializeObject<Config>(user.Config);
                        return OperResult<Config>.Succeed(temp);
                    }
                }
            }
            return OperResult<Config>.Failed("userCode is NULL");
        }



        private Config createDefaultConfig(MyContext context)
        {
            Config config = new();
            var list = context.OtherEnums.Where(u => u.Type == (int)OtherEnums.Config).ToList();
            config.BackImage = list[0].Text;
            config.TabBarImage = list[1].Text;
            config.RandomOrder = 0;
            config.Count = 0;
            config.NickName = "";
            config.MessageList = new();
            config.MessageLookId = 0;
            return config;
        }
    }
}
